package it.univpm.diiga.semanticsearch.ricerca;
import it.univpm.diiga.semanticsearch.configurazione.Configuration;
import it.univpm.diiga.semanticsearch.servizi.Link;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JOptionPane;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;


import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import org.w3c.dom.Element;


import com.sun.org.apache.xerces.internal.parsers.DOMParser;




public class RicercaRepository extends Ricerca {
    
	Document document=null;
    /*List<Document> docLocalList;
    List<Document> docDefalutList;
    List<Document> docPublicList;*/
    List<Document> documentList;
    List<String> repoName;
   
	public RicercaRepository(boolean localSearch, boolean defaultSearch, boolean publicSearch) throws Exception{
		//String xmlFile="repo.xml";
		boolean remoteExc=false;
		try{
			if (defaultSearch || publicSearch){
				Configuration.findRepoConfiguration();
			}
		}catch(Configuration.RemoteExc e){
			defaultSearch=false;
			publicSearch=false;
			remoteExc=true;
		}
		if (localSearch)
			Configuration.findLocalConfiguration();
		
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();	
		this.documentList=new ArrayList<Document>();
		this.repoName=new ArrayList<String>();
			for (int i=0; defaultSearch && i<getDefaultRepo().size() ; i++){
				DocumentBuilder db = dbf.newDocumentBuilder();
		
				
				URL url = getDefaultRepo().get(i);   
				URLConnection uc=url.openConnection();
				uc.setConnectTimeout(10000);
				uc.connect();
				InputStream inputStream = url.openStream();
				
	
			
				this.documentList.add(db.parse(inputStream));
				this.repoName.add(url.toString());
				
				inputStream.close();
			}	
			
			for (int i=0;  publicSearch && i<getPublicRepo().size(); i++){
				DocumentBuilder db = dbf.newDocumentBuilder();
				

				URL url = getPublicRepo().get(i); 
				URLConnection uc=url.openConnection();
				uc.setConnectTimeout(10000);
				uc.connect();
				InputStream inputStream = url.openStream();
					
			
				this.documentList.add(db.parse(inputStream));
				this.repoName.add(url.toString());
				
				inputStream.close();
			}	
			
			//for (int i=0;  localSearch && i<getLocalRepo().size(); i++){
				if (localSearch){
				DocumentBuilder db = dbf.newDocumentBuilder();
				
  				//System.getProperties().put( "proxyHost", proxy.getText() );
  				//System.getProperties().put( "proxyPort", proxyPort.getText());

				//File file = getLocalRepo().get(i);
				File file =getLocalRepo();
				if (file!=null){
					/*URLConnection uc=url.openConnection();
					uc.setConnectTimeout(10000);
					uc.connect();*/
					InputStream inputStream=null;
					try{
						inputStream = new FileInputStream (file);
						this.documentList.add(db.parse(inputStream));
						this.repoName.add(file.getName());
					}
					catch(Exception e){
						JOptionPane.showMessageDialog(null, "Wrong local file name","Error", JOptionPane.ERROR_MESSAGE);
					}
				
					finally{
						if (inputStream!=null)
							inputStream.close();
					}
				}
			}	
			/*if (remoteExc)
				throw new Configuration.RemoteExc();*/

	}
    
	
	public List<Link> execSearch(String keyword) {
		String wsdl="";
		String bpel="";
		String swsal="";
		String servLink="";
		String servName="";
		String servRepo="";
		
		keyword=keyword.toLowerCase();
		
		List<Link> lista=new ArrayList<Link>();
		
		for (int j=0; j<documentList.size(); j++){
			

		
			 	//Element rootEle = document.getDocumentElement();
				  Element rootEle= documentList.get(j).getDocumentElement();
	
			 
			 	NodeList list_serv = rootEle.getElementsByTagName("service");
				for(int i = 0 ; i < list_serv.getLength();i++) {
	
					Element service = (Element)list_serv.item(i);
					
					                 
					
					NodeList list_ele = service.getElementsByTagName("name");
	                if(list_ele != null && list_ele.getLength() > 0) {
	                    Element ele = (Element)list_ele.item(0);
	                   
	                    
	                    if (ele.hasChildNodes()){ // if node exist
	                     servName = ele.getFirstChild().getNodeValue().toLowerCase();
	                    
	                     
	     				
	                    }else{servName = "undefined";} // invalid xml agenda entry(blank name)
	                }
	                
	                if (!servName.equals("undefined") && servName.indexOf(keyword)>-1){               	
	                	//System.out.println((i+1)+": Caratteristiche trovate per il servizio "+name);
	                	list_ele = service.getElementsByTagName("wsdl");
	                    if(list_ele != null && list_ele.getLength() > 0) {
	                        Element ele = (Element)list_ele.item(0);
	                        if (ele.hasChildNodes()){ // if node exist
	                         wsdl = ele.getFirstChild().getNodeValue();
	                         servRepo=this.repoName.get(j).toString();
	                        // System.out.println("   Wsdl: "+wsdl);
	                        }else{wsdl =null;} // invalid xml agenda entry(blank name)
	                    }	
	                    
	                    
	                    
	                	list_ele = service.getElementsByTagName("bpel");
	                    if(list_ele != null && list_ele.getLength() > 0) {
	                        Element ele = (Element)list_ele.item(0);
	                        if (ele.hasChildNodes()){ // if node exist
	                         bpel = ele.getFirstChild().getNodeValue();
	                       //  System.out.println("   Bpel: "+bpel);
	                        }else{bpel =null;} // invalid xml agenda entry(blank name)
	                    }
	                    
	                	list_ele = service.getElementsByTagName("swsal");
	                    if(list_ele != null && list_ele.getLength() > 0) {
	                        Element ele = (Element)list_ele.item(0);
	                        if (ele.hasChildNodes()){ // if node exist
	                         swsal = ele.getFirstChild().getNodeValue();
	                       //  System.out.println("   Swsal: "+swsal);
	                        }else{swsal =null;} // invalid xml agenda entry(blank name)
	                    }
	                    
	                	list_ele = service.getElementsByTagName("servLink");
	                    if(list_ele != null && list_ele.getLength() > 0) {
	                        Element ele = (Element)list_ele.item(0);
	                        if (ele.hasChildNodes()){ // if node exist
	                         servLink = ele.getFirstChild().getNodeValue();
	                       //  System.out.println("   Link servizio: "+servLink);
	                        }else{servLink =null;} // invalid xml agenda entry(blank name)
	                    }
	                    
	                    Link serv=new Link(servName,servLink,wsdl,bpel,swsal,servRepo);
	                    
	                    lista.add(serv);
	                }
	                
	                	
	                		 
				}
		}
						
		return lista;
			
	}
	
	
}
